import axios from "axios";
import { errorCatch, getContentType } from "./api.helper";
import { useRouter } from "next/navigation";
import { useEffect } from "react";
import Router from "next/router";


export const instance = axios.create({
    withCredentials: true,
    baseURL: '/api',
    headers: getContentType()
})

instance.interceptors.request.use(
    (config) => {
        config.headers.Authorization = localStorage.getItem("token")
        return config
    }
)

let isRefreshing: boolean = false

instance.interceptors.response.use(
    (config) => {
        return config;
    },
    async error => {
        const originalRequest = error.config
        if (error.response.status == 401 && error.config && !(error.config._isRetry == true)) {
            if (!isRefreshing) {
                isRefreshing = true
                originalRequest._isRetry = true
                try {
                    const resp = await instance.get("/auth/refresh-tokens");
                    localStorage.setItem("token", resp.data.accessToken);
                    console.log("Tokens refreshed")
                    return instance.request(originalRequest);
                } catch (e) {
                    localStorage.removeItem('isAuth')
                    window.location.replace('/auth')
                } finally {
                    isRefreshing = false
                }
            }
        }
        throw error
    }
);